<?php
namespace app\index\controller;

use think\facade\View;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;

/**
 * 知识笔记存储
 */
class Knowledge extends Front
{
    public function index()
    {
        $pwd = Request::param('pwd');

        if($pwd=='asd123join'){
            Session::set('user','1');
        }
        
        $q = Request::param('q');
        $list = [];
        if($q){
            $list = Db::name('knowledge')
            ->where('keywords','like',"%$q%")
            ->select();
        }else{
            $list = Db::name('knowledge')
            ->order('create_time desc')
            ->limit(10)
            ->select();
        }
        View::assign('list',$list);
        return View::fetch('index');
    }
    public function create()
    {
        $user = Session::get('user');
        if(!$user){
            goto after;
        }
        $data = Request::param();
        $data['content'] = str_replace("\n", "<br/>", $data['content']);
        $data = \app\index\model\Knowledge::create($data);
        if(request()->isPost()){
            if(!$data->id){
                return json([
                    'code'=>0,
                    'msg'=>'失败!'
                ]);
            }else{
                return json([
                    'code'=>1,
                    'msg'=>'成功!',
                    'data'=>$data
                ]);
            }
        }
        after:
        //记录ip
        return json([
            'code'=>0,
            'msg'=>'非法请求!'
        ]);
    }
}
